package com.woniuxy.propertyjava.controller;

import com.woniuxy.propertyjava.entity.ResponseResult;
import com.woniuxy.propertyjava.entity.Staffimage;
import com.woniuxy.propertyjava.service.StaffimageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : author
 * @create 2022/7/8 15:06
 */
@RestController
public class ImageController {

    @Value("${upload.resourceHandler}")
    private String resourceHandler;

    @Value("${upload.resourceLocations}")
    private String resourceLocations;

    @Resource(type = StaffimageService.class)
    StaffimageService staffimageService;

    @PostMapping("/upload")
    public ResponseResult upload(@RequestBody MultipartFile file, @RequestParam("staffid") int staffid) throws IOException {
//        文件名去重
//        目录打散
        File newFile = new File(resourceLocations, file.getOriginalFilename());
        file.transferTo(newFile);

//        修改数据库图片地址
        Staffimage staffimage = new Staffimage();
        staffimage.setStaffid(staffid);
        String newImageSrc = "http://localhost:8080/images/" + file.getOriginalFilename();
        staffimage.setImagesrc(newImageSrc);
        staffimageService.updateStaffimage(staffimage);

//        响应
        ResponseResult responseResult = new ResponseResult<>(200, "上传图片成功", null);
        return responseResult;
    }

    @GetMapping("/image")
    public ResponseResult getStaffimageByStaffId(@RequestParam("staffid") int staffid) {
        Staffimage staffimage = staffimageService.getStaffimageByProperty(staffid);
        return new ResponseResult<>(200, "获取头像成功", staffimage);
    }


}
